package hot100;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class Lc15 {
    public List<List<Integer>> threeSum(int[] nums) {
        int[] array = Arrays.stream(nums).sorted().toArray();
        List<List<Integer>> res = new ArrayList<>();
        for (int i = 0; i < array.length - 2; i++) {
            if (i > 0 && array[i] == array[i - 1]) {
                continue;
            }
            int j = i + 1;
            int k = array.length - 1;
            while (j < k) {
                if (array[i] + array[j] + array[k] == 0) {
                    List<Integer> list = new ArrayList<>();
                    list.add(array[i]);
                    list.add(array[j]);
                    list.add(array[k]);
                    res.add(list);
                    while (j < array.length - 1 && array[j] == array[j + 1]) {
                        j++;
                    }
                    while (k > j && array[k] == array[k - 1]) {
                        k--;
                    }
                    k--;
                }
                else if (array[i] + array[j] + array[k] < 0) {
                    j++;
                }
                else {
                    k--;
                }
            }
        }
        return res;
    }
}
